package util

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)
type Claims struct {
	Uid int `json:"uid"`
	Username string `json:"username"`
	Password string `json:"password"`
	jwt.StandardClaims
}
/***
生成token
 */
func GenerateToken(d map[string]interface{}) (string,error){
	now := time.Now()
	expireTime := now.Add(240*time.Hour)
	claims := Claims{
		d["uid"].(int),
		d["username"].(string),
		d["password"].(string),
		jwt.StandardClaims{
			ExpiresAt:expireTime.Unix(),
			Issuer:"my-gin-bc",
		},
	}

	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256,claims)

	jwtScrect := []byte(config().App.JwtSecret)

	token,err := tokenClaims.SignedString(jwtScrect)
	if err !=nil{
		fmt.Println(err)
	}
	return token,err
}
/**
解析token
 */
func ParseToken(token string) (*Claims,error){
	tokenClaims ,err := jwt.ParseWithClaims(token,&Claims{}, func(token *jwt.Token) (i interface{}, e error) {
		return []byte(config().App.JwtSecret),nil
	})

	if tokenClaims != nil{

		// && tokenClaims.Valid
		if claims,ok:=tokenClaims.Claims.(*Claims);ok{
			return claims,nil
		}else{
			return nil,claims.Valid()
		}
	}
	return nil ,err
}